package com.kgar.service.impl;

import cn.hutool.core.util.StrUtil;
import com.kgar.dto.Result;
import com.kgar.service.UploadService;
import com.kgar.util.AliOSSUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import javax.annotation.Resource;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@Slf4j
@Service
public class UploadServiceImpl implements UploadService {
    @Resource
    private AliOSSUtil aliOSSUtil;

    @Override
    public Result uploadImage(MultipartFile image) {
        try {
            String url = uploadFile(image, "icon");
            log.debug("头像上传成功，{}", url);
            //返回oss地址
            return Result.ok(url);
        } catch (IOException e) {
            throw new RuntimeException("头像上传失败", e);
        }

    }

    @Override
    public Result uploadResume(MultipartFile resume) {
        try {
            String url = uploadFile(resume, "resume");
            log.debug("简历上传成功，{}", url);
            return Result.ok(url);

        } catch (IOException e) {
            throw new RuntimeException("简历上传失败", e);
        }
    }

    @Override
    public Result deleteFile(Map<String, List<String>> files) {

        List<String> urls = files.get("fileUrls");
        for (String fileName : urls) {
            aliOSSUtil.deleteFile(fileName);
        }
        return Result.ok();
    }


    private String uploadFile(MultipartFile file, String dirPath) throws IOException {

        // 获取原始文件名称
        String originalFilename = file.getOriginalFilename();
        // 生成新文件名
        String fileName = createNewFileName(originalFilename, dirPath);

        //保存oss
        // 返回结果
        return aliOSSUtil.uploadFile(file.getInputStream(), fileName);
    }

    private String createNewFileName(String originalFilename, String dirPath) {
        // 获取后缀
        String suffix = StrUtil.subAfter(originalFilename, ".", true);
        // 生成目录
        String name = UUID.randomUUID().toString();
        int hash = name.hashCode();
        int d1 = hash & 0xF;
        int d2 = (hash >> 4) & 0xF;
        return StrUtil.format("{}/{}/{}/{}.{}", dirPath, d1, d2, name, suffix);
    }




}
